package com.hxut.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * description: CrosConfig跨域配置
 * date: 2022/6/22 20:19
 * author: MR.孙
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");   //设置放行哪些原始域
        corsConfiguration.addAllowedHeader("*");   //放行哪些原始请求头部信息
        corsConfiguration.addAllowedMethod("*");  //放行哪些请求方式
        corsConfiguration.addExposedHeader("Authorization");    //暴露哪些头部信息
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        // 添加映射路径
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
//          .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                .maxAge(3600);//响应前的缓存持续的最大时间
    }
}
